class RequirementsController < ApplicationController
  before_filter :login_required

  #layout "projects"

  protect_from_forgery :except => :change_developer_finish

  in_place_edit_for :requirement, :priority

  def index
    unless params[:user_id] == nil
      @user = User.find(params[:user_id])
      @requirements = @user.requirements.unfinished_requirements
    else
      @project = Project.find(params[:project_id])
      @requirements = @project.requirements.all
      render :layout => "list"
    end
  end

  def new
    @requirement = Requirement.new
    @project = Project.find(params[:project_id])

    respond_to do |format|
      format.html
    end
  end

  def create
    @requirement = Requirement.new(params[:requirement])
    @requirement.project_id = params[:project_id]
    @project = Project.find(params[:project_id])
    @requirement.reqid = @project.current_req_index
    @project.current_req_index = @project.current_req_index + 1
    
    respond_to do |format|
      if @project.save && @requirement.save
        flash[:notice] = 'requirement was successfully created.'
        format.html { redirect_to(@requirement) }
      else
        format.html { render :action => "new" }
      end
    end
  end

  def show
    @req = Requirement.find(params[:id])
  end

  def edit
    @requirement = Requirement.find(params[:id])
  end

  def update
    @requirement = Requirement.find(params[:id])

    respond_to do |format|
      if @requirement.update_attributes(params[:requirement])
        flash[:notice] = 'requirement was successfully updated.'
        format.html { redirect_to(@requirement) }
      else
        format.html { render :action => "edit" }
      end

    end
  end

  def change_state
    @req = Requirement.find(params[:id])
    @op_code = params[:op_code]

    if @op_code.include?("working") || @op_code.include?("hang_up") || @op_code.include?("rework")
      eval "@req.#{@op_code}"
    end

    redirect_to :back
  end

  def change_developer
    @users = User.get_roles_users("developer", "pdm")
    @req = Requirement.find(params[:id])
    render :layout => false
  end

  def change_developer_finish
    @req = Requirement.find(params[:id])
    @user = User.find(params[:user_id])
    @req.user = @user
    @req.save

    url =  url_for :controller => 'requirements', :action => 'show', :id => @req
    MailingsWorker.asynch_send_mailing(:way => "req", :user_id => @user.id, :req_id => @req.id, :url => url)

    render :layout => false
  end

end
